package com.funcourse.demo.api.restful.security;

import com.funcourse.demo.WechatConfigurationsHolder;
import com.funcourse.demo.WeletConfigurationsHolder;
import com.funcourse.demo.api.ApiSystemConstants;
import com.funcourse.demo.wechat.conf.WechatConfiguration;
import com.funcourse.demo.wechat.conf.WeletConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
@Slf4j
public class WeletConfigFilter implements Filter {

  private static final Pattern refererPattern = Pattern.compile("https?://(.*).chongya.fun");

  @Autowired
  WeletConfigurationsHolder weletConfigurationsHolder;

  @Override
  public void destroy() {

  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String weletApp = httpRequest.getHeader("WeletApp");
    if(null == weletApp){
      weletApp = "chongya";
    }
    WeletConfiguration weletConfiguration = weletConfigurationsHolder.getApps().get(weletApp);
    if(null == weletConfiguration){
      weletConfiguration = weletConfigurationsHolder.getApps().get("chongya");
    }
    request.setAttribute(ApiSystemConstants.SERVLET_ATTR_WELET_CONFIG, weletConfiguration);
    chain.doFilter(request, response);
  }

  @Override
  public void init(FilterConfig arg0) throws ServletException {

  }

}
